package com.sap.mobile.maf.samples.android.mafprovisioningsample;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources.NotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.sap.maf.tools.logon.logonmanager.LogonManager;
import com.sap.maf.tools.logon.logonmanager.LogonManager.LogonManagerException;
import com.sap.maf.tools.logon.logonui.ResourceIdResolver;
import com.sap.maf.tools.logon.logonui.ResourceIdResolver.ResourceGroupEnum;
import com.sap.maf.uicontrols.MAFSkinManager;
import com.sap.maf.uicontrols.MAFUIFactory;
import com.sap.maf.utilities.logger.MAFLogger;
import com.sybase.mo.MessagingClientException;

public class LockScreenActivity extends Activity {
	public static final int logonRequestCode = 100;
	public static final int applicationRequestCode = 200;
	public static final int preferenceRequestCode = 300;
	private final String TAG = "LockScreenActivity";
	private final String APPLICATIONID = "com.sap.maf.test.adr.logonapp";
	private static Activity act;
	private static boolean sampleMode;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		act=this;
		MAFSkinManager.getInstance(this).loadStyle("green",
				getResources().openRawResource(R.raw.styles));
		MAFSkinManager.getInstance(this).loadStyle("red",
				getResources().openRawResource(R.raw.styles_red));
		createUI();
		
		
	}

	private void createUI() {
		setContentView(R.layout.lock_screen);

		RelativeLayout mainLayout;
		DisplayMetrics dpm;
		mainLayout = ((RelativeLayout) findViewById(R.id.mainView));
		dpm = this.getResources().getDisplayMetrics();
		boolean xlarge = ((this.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
	    boolean large = ((this.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
	    
		
		if((int)((float)dpm.widthPixels/dpm.density)>360 && (xlarge || large)){
				
		 		mainLayout.setPadding((dpm.widthPixels-360)/2, 0, (dpm.widthPixels-360)/2, 0);
			}else{
				mainLayout.setPadding(0, 0, 0, 0);
			}
		MAFLogger.clearLogData();
		MAFLogger.logToAndroid(true);

		MAFUIFactory.getInstance().reskinUI(this);

		try {
			// Initialize the LogonManager by supplying the activity and the
			// application ID
			// which should be registered in the SUP backend
			try {
				LogonManager.init(this.getApplicationContext(), APPLICATIONID);
			} catch (MessagingClientException e) {
				MAFLogger.e(TAG, e.getMessage(), e);
			}
		} catch (LogonManagerException e) {
			MAFLogger.e(TAG, e.getMessage(), e);
		}

		// try {
		// if (LiteUserManager.getInstance().isRegistered()){
		// doShowApplicationScreen();
		// }
		// } catch (MessagingClientException e) {
		// MAFLogger.e(TAG, e.getMessage(), e);
		// }

		Button loginButton = (Button) findViewById(R.id.lock_screen_button_login);
		loginButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sampleMode=false;
				doShowLogonScreen();
			}
		});

		Button sampleDataButton = (Button) findViewById(R.id.lock_screen_button_sample_data);
		sampleDataButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sampleMode=true;
				doShowApplicationScreen();
			}
		});
		
		// It is needed to be exchanged the copyright char in the code
		// the reason is that the translation system accepts only ASCII chars
		try {

			final String resString = getResources().getString(
					R.string.sap_uex_gold_stripe_copyright);
			if (resString != "") {
				final String text = String.format(resString, '\u00A9');
				final TextView tv = (TextView) findViewById(R.id.sap_uex_gold_stripe_copyright);
				if (tv != null)
					tv.setText(text);
			}

		} catch (NotFoundException notFoundEx) {
			MAFLogger.i(TAG, notFoundEx.getMessage(), notFoundEx);
		}

	}

	private void doShowLogonScreen() {
		Intent logonIntent = new Intent(this, LogonActivity.class);
		startActivityForResult(logonIntent, logonRequestCode);
	}

	private void doShowApplicationScreen() {
		
		Intent logonIntent = new Intent(this, SampleTabActivity.class);
		logonIntent.removeExtra("sampleMode");
		logonIntent.putExtra("sampleMode", sampleMode);
		startActivityForResult(logonIntent, applicationRequestCode);
	}

	private void handleLogout() {
		try {
			LogonManager.resolveLogout();
		} catch (LogonManagerException e) {
			MAFLogger.e(TAG, e.getMessage());
		}
	}

	private void handleLock() {
		try {
			LogonManager.lockVault();
		} catch (LogonManagerException e) {
			MAFLogger.e(TAG, e.getMessage());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.preferences:
			// open the preferences screen
			startActivityForResult(new Intent(this,
					SamplePreferenceActivity.class), preferenceRequestCode);
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	@Override
	protected void onResume(){
		super.onResume();
		final SharedPreferences localPrefs = getSharedPreferences(
				getPackageName() + "_preferences", MODE_PRIVATE);
		final String styleName = localPrefs.getString("themeID", "welter");
		try {
			MAFSkinManager.getInstance(this).setActiveStyle(styleName);
		} catch (IllegalArgumentException e) {
			// $JL-EXC$
		}
		runOnUiThread(new Runnable() {
		    public void run() {
		    	MAFUIFactory.getInstance().reskinUI(act);
		    }
		});		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == logonRequestCode) {
			if (data != null) {
				if (data.getBooleanExtra("isLogoutStarted", false)) {
					handleLogout();
				} else if (data.getBooleanExtra("isUserLoggedOn", false)) {
					doShowApplicationScreen();
				}
			}
			
		} else if (requestCode == applicationRequestCode) {
			boolean isLogOutAction = false;

			if (data != null) {
				isLogOutAction = data.getBooleanExtra("isLogoutStarted", false);
			}

			if (isLogOutAction) {
				handleLogout();
			} else {
				handleLock();
			}

		}
	}

}
